<template>
    <rui-page :defines="defines">
        <div style="background-color: #f9fafc;">
            <Alert show-icon style="height: 30px;">
                <div style="margin-top:-2px">请输入查询条件</div>
            </Alert>
            <rui-query ref="searchForm" :query="queryData" :query-rows="searchFormLabels" />
        </div>
        <div class="search">
            <Row class="operation">
                <Col>
                    <Card>
                        <div style="margin-bottom:5px">
                            <Button type="primary" @click="delBtn">删除</Button>
                            <Button type="primary" @click="editBtn">编辑</Button>
                            <Button type="primary" @click="getTrialResultData">试算</Button>
                            <Button type="primary" @click="addRuleBtn">新增</Button>
                        </div>
                        <Row>
                            <Alert show-icon>
                                已选择 <span class="select-count">{{selectCount}}</span> 项
                                <a class="select-clear" @click="clearSelectAll">清空</a>
                            </Alert>
                        </Row>
                        <rui-table :loading="loading" border :defineId="'rulesdefineId'" @loadDatas="queryData" :showIndex="false" :select="true" :columns="columns" :data="data" :slots="[{key:'isOpen',slot:'isOpen'},{key:'status',slot:'status'}]" @on-selection-change="changeSelect" @on-sort-change="changeSort" ref-query="searchForm" ref="rulesTable">
                            <template slot="isOpen" slot-scope="{ row }">
                                <div>
                                    <Button v-if="row.isOpen==='no'" style="margin-right:5px" @click="openRule(row)" size="small" type="primary" icon="ios-create">启用</Button>
                                    <Button v-if="row.isOpen==='yes'" style="margin-right:5px" @click="closeRule(row)" size="small" type="error" icon="md-trash">停用</Button>
                                    <Button type="primary" @click="createRules(row)">配置激活规则</Button>
                                </div>
                            </template>
                            <template slot="status" slot-scope="{ row }">
                                <div>
                                    <span v-if="row.isOpen==='yes'">启用</span>
                                    <span v-if="row.isOpen==='no'">停用</span>
                                </div>
                            </template>
                        </rui-table>
                        <Modal v-model="activateVisible" :title="activateTitle" :closable="true" :mask-closable='true' :width="1000" :styles="{top: '180px'}">
                            <Row>
                                <rui-form :form-options="formOptions" :label-width="150" :read-only="false" ref="showForm" />
                            </Row>
                            <div slot="footer">
                                <Button size="small" @click="activateVisible = false">取消</Button>
                                <Button size="small" @click="saveRule">保存</Button>
                            </div>
                        </Modal>
                        <Modal v-model="activateCalculate" :title="modalTitle" :closable="false" :mask-closable='false' :width="1000" :styles="{top: '180px'}">
                            <div slot="footer" align="center">
                                <Button type="primary" @click="batchActivation">批量激活</Button>
                                <Button type="text" @click="activateCalculate = false">取消</Button>
                            </div>
                            <Row>
                                <Alert show-icon> 待激活案件试算 </Alert>
                                <Form ref="formAudit" :label-width="90" inline>
                                    <FormItem label="总贷款额:"><Input type="text" v-model="totalAmount" readonly /></FormItem>
                                </Form>
                                <Table :data="trialResultData" :columns="trialResultColumns" :show-header="true" size="small" stripe @on-sort-change="changeSorts" @on-selection-change="showSelect">
                                </Table>
                            </Row>
                            <Row type="flex" justify="end" class="page">
                                <Page :current="activateSearchFrom.pageNumber" :total="total" :page-size="activateSearchFrom.pageSize"
                                      @on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[10,20,50]"
                                      size="small" show-total show-elevator show-sizer></Page>
                            </Row>
                        </Modal>
                        <Modal v-model="rulesVisible" :title="ruleTitle" :closable="false" :mask-closable='false' :width="1000" :styles="{top: '180px'}">
                            <Row>
                                <rule-tree v-if="dataLoad" :rule-data="ruleData" :ruleAtoms="ruleAtoms" :ruleName="ruleName" :ruleGroup="ruleGroup" :businessScenario="businessScenario" @saved="updateRuleId" :rule-id="rule_Id" />
                            </Row>
                            <div slot="footer">
                                <Button size="small" @click="rulesVisible = false,dataLoad = false">取消</Button>
                            </div>
                        </Modal>
                    </Card>
                </Col>
            </Row>
        </div>
    </rui-page>
</template>
<script>
    import activateRulesTrialDefine from '../defines/loan-activate-rulestrial-define'
    import {
        getActivateRulesList,
        doActivateOfArtificial,
        addRule,
        editRule,
        delByIds,
        openRuleById,
        closeRuleById,
        updateRuleId,
        getTrialResultData,
        getTrialResultDatas
    } from '_p/afs-core-business/api/afs-case/loan-activate-rules-trial/loanActivateRulesTrial'
    import ruiRules from '_c/rui-auto/rui-rules/index'
    import { queryAtomsByBizType } from '_p/basic/api/rule/ruleAtom'
    import { loadRuleDataById } from '_p/basic/api/rule/rule'

    export default {
        name: 'loan-activate-rules-trial',
        components: {
            ruleTree: ruiRules,
        },
        data() {
            return {
                loading: true,
                modalTitle: '',
                ruleTitle: '',
                activateTitle: '',
                activateCalculate: false,
                activateVisible: false,
                rulesVisible: false,
                modalType: 0, // 判断是添加还是修改
                selectCount: 0,
                selectList:[],
                drop: false,
                data: [],
                total: 0,
                trialResultData: [],
                totalAmount: 0,
                activateSearchFrom:{
                    pageSize:10,
                    pageNumber:1
                },
                trialResultColumns: [
                    {
                        type: "selection",
                        minWidth: 60,
                        maxWidth:60,
                        align: "center",
                        fixed: "left",
                        slot: "selection"
                    },
                    {
                        title: '申请编号',
                        key: 'applyNo',
                    },
                    {
                        title: '业务类型',
                        key: 'businessType',
                        type: 'singleSelect',
                        dicKey: 'confBusinessType',
                    },
                    {
                        title: '客户姓名',
                        key: 'custName',
                    },
                    {
                        title: '经销商',
                        key: 'dealer',
                    },
                    {
                        title: '区域',
                        key: 'area',
                    },
                    {
                        title: '贷款额',
                        key: 'loanAmounts',
                    },
                ],
                searchFormLabels: [
                    {
                        defineId: 'rulesdefineId',
                        span: 8,
                        fields: [
                            'rulesName',
                            'rulesDesc',
                            'isOpen',
                            'createBy',
                            'effectTime',
                            'uneffectTime',
                        ],
                    },
                ],
                formOptions: [
                    {
                        grids: [
                            {
                                defineId: 'rulesdefineId',
                                span: 10,
                                fields: ['rulesNameDisplay', 'rulesDescDisplay'],
                            },
                        ],
                    },
                ],
                columns: [
                    'isOpen',
                    'rulesName',
                    'rulesDesc',
                    'effectTime',
                    'uneffectTime',
                    'rulesId',
                    'status'
                ],
                ruleAtoms: [],
                ruleTree: [],
                fitScope: 'loanActiveRule',
                path: 'case',
                ruleName: '放款规则配置',
                ruleGroup: 'activateRuleGroup',
                businessScenario: 'businessScenario',
                dataLoad: false,
                ruleData: [],
                rule_Id: null,
                row: {},
            }
        },
        computed: {
            defines() {
                return [{ id: 'rulesdefineId', fields: activateRulesTrialDefine }]
            },
        },
        methods: {
            refresh() {
                this.$refs['rulesTable'].reloadData()
            },
            queryData(queryData) {
                // 多条件搜索用户列表
                this.loading = true
                getActivateRulesList(queryData).then((res) => {
                    if (res.code === '0000') {
                        let { records, total } = res.data
                        this.$refs.rulesTable.updateTableData(records, total)
                    }
                })
                queryAtomsByBizType(this.fitScope, this.path).then((res) => {
                    if (res.code === '0000') {
                        this.ruleAtoms = res.data
                    }
                })
            },
            showSelect(e) {
                this.selectList = e;
                this.selectCount = e.length;
                let number =0;
                this.selectList.forEach(column=>{
                    number=number + column.loanAmounts
                })
                this.totalAmount=number;
            },
            changePage(v) {
                this.activateSearchFrom.pageNumber = v
                this.getTrialResultData()
                this.clearSelectAll()
            },
            changePageSize(v) {
                this.activateSearchFrom.pageSize = v
                this.getTrialResultData()
            },
            createRules(row) {
                if (row.isOpen === 'yes') {
                    this.$Message.warning('不可操作已启用的规则')
                    return
                }
                this.row=row;
                this.$refs.showForm.resetFrom()
                //加载规则数据
                if (row.rulesId && row.rulesId != '') {
                    loadRuleDataById(row.rulesId, this.path).then((res) => {
                        if (res.code === '0000') {
                            if (res.data.length > 0) {
                                this.ruleData = res.data
                            }
                            this.dataLoad = true
                            this.rule_Id = row.rulesId
                        }
                    })
                } else {
                    this.rule_Id = null
                    this.ruleData = []
                    this.dataLoad = true
                }
                this.businessScenario = row.id
                this.ruleTitle = '激活规则配置'
                this.row = row
                this.rulesVisible = true
            },
            editBtn() {
                if (this.selectCount <= 0) {
                    this.$Message.warning('您还未选择要编辑的数据')
                    return
                } else if (this.selectCount > 1) {
                    this.$Message.warning('请勾选单条数据进行编辑操作')
                    return
                }
                this.modalType = 1 //编辑状态
                this.activateTitle = '编辑规则描述'
                let row
                this.selectList.forEach((e) => {
                    row = e
                    row.rulesNameDisplay = e.rulesName
                    row.rulesDescDisplay = e.rulesDesc
                })
                this.$refs.showForm.updateFormData(row)
                this.$refs.showForm.setAllFieldRequired(true)
                this.activateVisible = true
            },
            addRuleBtn() {
                this.modalType = 0 //新增状态
                this.$refs.showForm.resetFrom()
                this.$refs.showForm.setAllFieldRequired(true)
                this.activateTitle = '新增激活规则'
                this.activateVisible = true
            },
            saveRule() {
                this.$refs.showForm.getForm().validate((valid) => {
                    if (valid) {
                        let param = this.$refs.showForm.getFormData()
                        param.rulesName = param.rulesNameDisplay
                        param.rulesDesc = param.rulesDescDisplay
                        if (this.modalType === 0) {
                            param.isOpen = 'no'
                            addRule(param)
                                .then((res) => {
                                    if (res.code === '0000') {
                                        this.$Message.success(res.msg)
                                        this.refresh()
                                        this.activateVisible = false
                                    }
                                })
                                .catch(() => {
                                    this.refresh()
                                })
                        } else {
                            // 编辑
                            editRule(param)
                                .then((res) => {
                                    if (res.code === '0000') {
                                        this.$Message.success(res.msg)
                                        this.refresh()
                                        this.activateVisible = false
                                    }
                                })
                                .catch(() => {
                                    this.refresh()
                                })
                        }
                    }
                })
            },
            delBtn() {
                if (this.selectCount <= 0) {
                    this.$Message.warning('您还未选择要删除的数据')
                    return
                }
                let ids = []
                let rules = false
                this.selectList.forEach((e) => {
                    if (e.isOpen === 'yes') {
                        rules = true
                        return
                    }
                    ids += e.id + ','
                })
                if (rules) {
                    this.$Message.warning('不可操作已启用的规则')
                    return
                }
                this.$Modal.confirm({
                    title: '确认删除',
                    content: '您确认要删除所选的 ' + this.selectCount + ' 条数据?',
                    onOk: () => {
                        ids = ids.substring(0, ids.length - 1)
                        delByIds(ids).then((res) => {
                            if (res.code === '0000') {
                                this.$Message.success(res.msg)
                                this.clearSelectAll()
                                this.refresh()
                            }
                        })
                    },
                })
            },
            calculate() {
                if (this.selectCount <= 0) {
                    this.$Message.warning('您还未选择要试算的数据')
                    return
                } else if (this.selectCount > 1) {
                    this.$Message.warning('请勾选单条数据进行试算操作')
                    return
                }
                let rules = false
                let row
                this.totalAmount = 0
                this.selectList.forEach(function (e) {
                    if (e.isOpen != 'yes') {
                        rules = true
                        return
                    }
                    row = e
                })
                if (rules) {
                    this.$Message.warning('规则未启用无法进行规则试算.')
                    return
                }
                if (row.rulesId && row.rulesId != '') {
                    this.getTrialResultData();
                    this.activateCalculate = true
                } else {
                    this.$Message.warning('您还未配置该条数据的激活规则')
                }
            },
            getTrialResultData(){
                getTrialResultDatas(this.activateSearchFrom).then((res) => {
                    if (res.code === '0000' && res.data) {
                        console.log(res.data)
                        this.trialResultData = res.data.records
                        this.total=res.data.total;
                        this.activateCalculate = true
                        // res.data.records.forEach((element) => {
                        //   this.totalAmount = this.totalAmount + element.loanAmounts
                        // })
                    }
                })
            },
            batchActivation() {
                var ids =[];
                console.log(this.selectList)
                this.selectList.forEach(function (e) {
                    ids.push(e.id);
                });
                console.log(ids)
                doActivateOfArtificial(ids).then((res) => {
                    if (res.code === '0000' ) {
                        this.$Message.success("操作成功！")
                    }
                })
            },
            clearSelectAll() {
                this.$refs.rulesTable.getTable().selectAll(false)
            },
            changeSelect(e) {
                this.selectList = e
                this.selectCount = e.length
            },
            changeSorts(e) {
                this.searchForm.sort = e.key
                this.searchForm.order = e.order
                if (e.order === 'normal') {
                    this.searchForm.order = ''
                }
                this.refresh()
            },
            changeSort(e) {
                this.searchForm.sort = e.key
                this.searchForm.order = e.order
                if (e.order === 'normal') {
                    this.searchForm.order = ''
                }
                this.refresh()
            },
            openRule(row) {
                if (!row.rulesId || row.rulesId == '') {
                    this.$Message.warning('您还未配置规则无法启用该条规则.')
                    return
                }
                this.$Modal.confirm({
                    title: '确认启用',
                    content: '您确认要启用规则【' + row.rulesName + '】?',
                    onOk: () => {
                        openRuleById(row.id).then((res) => {
                            if (res.code === '0000') {
                                this.$Message.success(res.msg)
                                this.refresh()
                            }
                        })
                    },
                })
            },
            closeRule(row) {
                this.$Modal.confirm({
                    title: '确认停用',
                    content: '您确认要停用规则【' + row.rulesName + '】?',
                    onOk: () => {
                        closeRuleById(row.id).then((res) => {
                            if (res.code === '0000') {
                                this.$Message.success(res.msg)
                                this.refresh()
                            }
                        })
                    },
                })
            },
            updateRuleId(ruleId) {
                this.row.rulesId=ruleId;
                updateRuleId(this.row)
                    .then((res) => {
                        if (res.code === '0000') {
                            this.$Message.success(res.msg)
                            this.refresh()
                            this.rulesVisible = false
                            this.dataLoad = false
                        }
                    })
                    .catch(() => {
                        this.refresh()
                    })

            },
        },
        mounted() {
            this.refresh()
        },
    }
</script>
